//
//  FHOauthViewController.swift
//  FHweibo
//
//  Created by 张嵩雷 on 16/4/9.
//  Copyright © 2016年 feng. All rights reserved.
//

import UIKit

import SVProgressHUD

class FHOauthViewController: UIViewController {
    
    ///在loadView里面赋值不用设置view的大小
    override func loadView() {
        view = webView
        
        //设置webView代理
        webView.delegate  = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置背景颜色,不然在modal出来的时候会透明看到后面的控制器,效果很奇怪
        view.backgroundColor = GlobalBGColor
        
        setupNavigationBar()
        
        //加载授权界面
        let url = oauthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
        //添加指示器//        SVProgressHUD.showErrorWithStatus("你错了", maskType: SVProgressHUDMaskType.Gradient)    // 叉
        //        SVProgressHUD.showSuccessWithStatus("你成功了", maskType: SVProgressHUDMaskType.None)     //勾
        //        SVProgressHUD.showInfoWithStatus("showInfo", maskType: SVProgressHUDMaskType.None)        // 感叹号 i
        SVProgressHUD.showWithStatus("正在加载登录界面...")//进度转,一直存在不消失,除非调用dismiss
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
        
    }
    
    ///拼接Oauth授权登录界面的url(get)
    private func oauthURL()->NSURL {
        
        let urlString = OauthUrl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        print(urlString)
        
        return NSURL(string: urlString)!
    }
    
    ///设置导航栏左右两边的填充和取消按钮
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("autoFill"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("close"))
    }
    
    //MARK: - 按钮点击事件
    //填充按钮
    @objc private func autoFill() {
       //使用webView执行js代码
        let js = "document.getElementById('userId').value = '920676024@qq.com';document.getElementById('passwd').value = 'fenghun1991'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //取消按钮
    @objc private func close() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
   //MARK: - 懒加载
    //webView
    private lazy var webView:UIWebView = UIWebView()
}

//MARK: - webView代理方法
extension FHOauthViewController: UIWebViewDelegate {
    // webView是否要去加载一个请求
    // true: 放行,可以加载
    // false: 拦住,不去加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
       
//        FHPrint("webView是否要去加载一个请求:\(urlString)")
        // 当如果是  http://www.baidu.com/ 开头的地址,我们自己来处理拦截不让他去加载,其他的地址放行
        // 点击取消按钮: https://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        // 点击授权: https://www.baidu.com/?code=f14220fceb084162dd787e7ea511008f
        
        //判断是否是授权回调地址
        let isRedirectURL = urlString!.hasPrefix(redirect_uri)
        
        if !isRedirectURL {
            //不是授权回调地址,让他加载
            return true
        }else {
            //授权回调地址,点击的是取消或授权
            //判断点击的是取消还是授权按钮,如果?后面code=开头就是授权按钮
            //query是get请求?后面的定向
            let query = request.URL?.query
//            FHPrint("query: \(query)")
            
            let codeString = "code="
            //判断query是否是code= 开头
            if query!.hasPrefix(codeString) {
                //query是以code=开头,授权按钮
//                FHPrint("授权那妞点击了:\(query)")
                // 截取 code=4e496956aa012e11299494637e9ca536 里面code=后面的内容
//                                let index = codeString.endIndex
//                                let code = query!.substringFromIndex(index)
                //截取字符串转成NSString
                let code = (query! as NSString).substringFromIndex(codeString.characters.count)
//                FHPrint("code:\(code)")
                 // 获取access_token,当使用POST获取AccessToken成功后下次输入密码不会弹出授权按钮，会直接去获取AccessToken,如果想看到授权按钮需要去取消授权
//                loadAccessToken(code)
                ///3.调用loadAccessToken,准备闭包并传递
                    FHUserAccountViewModel.sharedInstance.loadAccessToken(code, loadAccessTokenCallback: { (error) -> () in
                        
                        if error != nil {
                        FHPrint("加载accessToken出错了: \(error)")
                            
                            SVProgressHUD.showErrorWithStatus("网络不给力")
                            
                            //延时关闭
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                                self.close()
                            })

                            return
                        }
                        //成功了
//                        FHPrint("加载AccessToken成功了 ")
                        
                        self.close()
                        // 跳转到欢迎界面
                        let controller = FHWelcomeViewController()
                        (UIApplication.sharedApplication().delegate as! AppDelegate).switchViewController(controller)
                    })
            }else {
                //取消按钮
                FHPrint("取消按钮被点击了")
                //关闭控制器
                close()
            }
            return false
        }
    }
    

    
    
    ///webView加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    ///webView加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        //当设置showErrorWithStatus会将其他的HUDdismiss
        FHPrint("error:\(error)")
        if error?.code == 102 {
            //点击取消,加载被中断
            return
        }
        SVProgressHUD.showErrorWithStatus("网络不给力....")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
    }
    
}

